<?php
/**
 * Created by PhpStorm.
 * User: 17274
 * Date: 2018/3/27
 * Time: 21:06
 */
namespace app\admin\model\novel;

use app\admin\helper\DBhelper;
use app\admin\helper\LangHelper;
use app\admin\helper\SearchHelper;
use app\admin\model\BaseM;
use app\admin\model\LogsM;
use app\admin\popo\LayData;
use think\Config;
use think\Session;
use think\Validate;

class NovelVolumeM extends  BaseM
{
    protected $table = 'tb_novel_volume';
    protected $module = '卷名列表';

    /*
     * rule
     * 验证data
     * @params $data
     * 新增和修改时验证
     * */
    public function validate_model(){
        $post = input('post.');
        $rule = [
            'novel_id' => 'require',
            'title' => 'require',
        ];
        $msg = [
            'novel_id.require' => '__novel.validata.title.require__',
            'title.require' => '__novel_volume.validata.title.require__',
        ];
        $msg = LangHelper::convertLang($msg,'field');
        $validate = new Validate($rule, $msg);
        $result = $validate->check($post);
        if(!$result){
            return op_msg(0,$validate->getError());
        }
        return op_msg(1,'success');
    }

    /**
     * 前端search控件
     * button vale [ add edit del search export ]
     * @return mixed
     */
    public function __search(){
        $search = [
            'tag'=>['field'=>'tag','title'=>'__tag__','type'=>'input','value'=>''],
            'novel_id'=>['field'=>'novel_id','title'=>'__novel.title__','type'=>'select','value'=>'function:getNovelList'],
            'status'=>['field'=>'status','title'=>'__status__','type'=>'select','value'=>'function:getStatusList'],
            'created_at'=>['field'=>'created_at','title'=>'__created_at__','type'=>'date_range','value'=>'function:getMonthDateRange'],
            'button'=>['type'=>'button','value'=>['add','search','export']],
        ];
        SearchHelper::convertValue($search);
        $search['form'] = implode(',',array_keys($search));
        return LangHelper::convertLang($search,'field');
    }

    /**
     * 前端表格列
     * @return string
     */
    public function __header(){
        $header = [
            ['type'=>'checkbox'],
            ['field'=>'novel_name','title'=>'__novel.title__'],
            ['field'=>'title','title'=>'__novel_volume.title__'],
            ['field'=>'sort','title'=>'__sort__'],
            ['field'=>'status','title'=>'__status__'],
            ['field'=>'created_at','title'=>'__created_at__'],
            ['field'=>'updated_at','title'=>'__updated_at__'],
            ['field'=>'op','title'=>'__op__','toolbar'=>'#operate']
        ];
        return json_encode(LangHelper::convertLang($header,'field'));
    }

    /**
     * list All Data  status=1
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function listAll($novel_id){
        return $this->field('id,title')->where(["novel_id"=>$novel_id,'status'=>1])->order('created_at desc')->select();
    }

    /*
     * 列表
     * */
   public function listData(){
       $page=input("post.page/d");
       $limit=input("post.limit/d");
       $tag=input("post.tag/s");
       $time=input("post.created_at/s");
       $start = strtotime(explode(' - ',$time)[0]);
       $end = strtotime(explode(' - ',$time)[1]);

       $where = [
           'a.title|b.title'=>['like',"%".$tag."%"],
           'a.created_at'=>['between', [$start, $end+86399]]
       ];
       $status=input("post.status/d");
       if ($status>0) {
           $where['a.status'] = $status;
       }

       $novel_id=input("post.novel_id/d");
       if ($novel_id>0) {
           $where['a.novel_id'] = $novel_id;
       }

       $log = [
           'op_uid' => Session::get('username'),
           'op_module' => $this->module,
           'op_type' => 'search',
           'op_origin' => $this->table,
           'op_data' => json_encode($where,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
           'op_ip' => getIP(),
       ];
       //export逻辑
       if (input("post.export/b")) {
           $header = json_decode($this->__header(),true);
           $column = [];
           foreach ($header as $v) {
               if (!isset($v['field']) || $v['field'] == 'op' || $v['field'] == 'novel_name')
                   continue;
               $column[] = 'a.'.$v['field'];
           }
           $column = implode(',',$column);
           $export_data = $this->alias('a')->field($column.',b.title novel_name')
               ->join('tb_novel b','a.novel_id = b.id','left')
               ->where($where)->order('a.created_at desc,a.sort desc')->select()->toArray();
           $log['op_type'] = 'export';
           $log['op_data'] = json_encode($header,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
           $log['op_sql'] = $this->getLastSql();
           LogsM::add($log);
           pr_log($log,'operate');
           export('小说卷名列表',$export_data,$header);
       }
       $resp = new LayData();
       $resp->count = $this->alias('a')->join('tb_novel b','a.novel_id = b.id','left')->where($where)->count();
       $resp->data = $this->alias('a')->field('a.*,b.title novel_name')
           ->join('tb_novel b','a.novel_id = b.id','left')
           ->where($where)->order('a.created_at desc,a.sort desc')->page($page,$limit)->select();
       $resp->extra_data = Config::get('app_debug')?self::getLastSql():'';
       $log['op_sql'] = $this->getLastSql();
       LogsM::add($log);
       pr_log($log,'operate');
       return $resp;
   }

   public function getLastSort($novel_id){
       $where['novel_id'] = $novel_id;
       $lastSort = $this->field('sort')->where($where)->order('sort desc')->find();
       return empty($lastSort)?1:$lastSort['sort']+1;
   }

    /*
     * 新增
     * */
    public function add(){
        $data=input('post.');
        unset($data['method']);
        $data['created_at']=time();
        $data['updated_at']=time();
        $re = $this->save($data);
        $last_sql = Config::get('app_debug')?$this->getLastSql():'';
        if($re){
            $log = [
                'op_uid' => Session::get('username'),
                'op_module' => $this->module,
                'op_type' => 'add',
                'op_origin' => $this->table,
                'op_data' => $data['title'],
                'op_ip' => getIP(),
                'op_sql' => $this->getLastSql(),
            ];
            LogsM::add($log);
            pr_log($log,'operate');
            return op_success($last_sql);
        }
        return op_fail($last_sql);
    }

    /*
     * 修改
     * */
    public function edit(){
        $data=input('post.');
        $id=$data['id'];
        unset($data['method']);
        //只修改变化字段
        $origin = $this->getById($id)->toArray();
        $data = DBhelper::getChangeData($data,$origin);
        if (!empty($data)){
            $data['updated_at']=time();
            $re = $this->where('id',$id)->update($data);
            $last_sql = Config::get('app_debug')?$this->getLastSql():'';
            if($re){
                $log = [
                    'op_uid' => Session::get('username'),
                    'op_module' => $this->module,
                    'op_type' => 'edit',
                    'op_origin' => $this->table,
                    'op_data' => json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
                    'op_ip' => getIP(),
                    'op_sql' => $this->getLastSql(),
                ];
                LogsM::add($log);
                pr_log($log,'operate');
                return op_success($last_sql);
            }
            return op_fail($last_sql);
        }
        return op_nochange();
    }

    /*
     * 删除
     * */
    public function del(){
        $ids=input('post.ids/a');
        $op_name=[];
        foreach ($ids as $id){
            $name = $this->getById($id)->toArray()['title'];
            array_push($op_name,$name);
        }
        if (!empty($op_name)) {
            //事务开始
            $this->startTrans();
            $re = $this->destroy($ids);
            $last_sql = Config::get('app_debug')?self::getLastSql():'';
            if ($re){
                //删除相应章节
                if (NovelChapterM::delByVolumeId($ids)) {
                    $this->commit();
                    $log = [
                        'op_uid' => Session::get('username'),
                        'op_module' => $this->module,
                        'op_type' => 'delete',
                        'op_origin' => $this->table,
                        'op_data' => json_encode($op_name,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
                        'op_ip' => getIP(),
                        'op_sql' => $this->getLastSql(),
                    ];
                    LogsM::add($log);
                    pr_log($log,'operate');
                    return op_success($last_sql);
                }
            }
            $this->rollback();
            return op_fail($last_sql);
        }
        return op_superadmin();
    }

    public static function delByNoveId($novel_id){
        $mod = new self();
        $novel_id = "'".implode("','",$novel_id)."'";
        $volumeList = $mod->field('id')->where("novel_id in ($novel_id) ")->select()->toArray();
        if (!empty($volumeList)){
            //事务开始
            $mod->startTrans();
            //删除相应卷
            if ($mod->where("novel_id in ($novel_id) ")->delete()) {
                //删除相应章节
                $volume_id = array_column($volumeList,'id');
                if (NovelChapterM::delByVolumeId($volume_id)) {
                    $mod->commit();
                    return 1;
                }
            }
            $mod->rollback();
            return 0;
        }
        return 1;
    }

}